import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/token'
import { isHttp, isEmpty } from "@/utils/validate"
// import defAva from '@/assets/images/profile.jpg'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      role: '',
      userInfo: '',
      permissions: []
    }),
    actions: {
      // 登录
      login(userInfo) {
        userInfo.username = userInfo.username.trim();
        return new Promise((resolve, reject) => {
          login(userInfo).then(res => {
            setToken(res.data.token)
            this.token = res.data.token
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res.data.user
            let avatar = user.avatar || ""
            // if (!isHttp(avatar)) {
            //   avatar = (isEmpty(avatar)) ? defAva : import.meta.env.VITE_APP_BASE_API + avatar
            // }
            if (user.role) { // 验证返回的role是否是一个非空
              this.role = user.role;
              this.permissions = res.data.permissions;
            } else {
              this.role = 'ROLE_ADMIN'
            }
            this.id = user.uid
            this.name = user.userName
            this.avatar = avatar
            this.userInfo = res.data.user;
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout().then(() => {
            this.token = ''
            this.roles = ''
            // this.permissions = []
            removeToken()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      }
    }
  })

export default useUserStore
